#include <unistd.h>
#include <linux/ip.h>
#include <string.h>
#include <time.h>

#include "opendpi_packets_top5.h"
#include "sql.h"
#include "protocols.h"
#include "log.h"
#include "msg.h"

extern char *prot_long_str[]; 
#define IPOQUE_MAX_SUPPORTED_PROTOCOLS 118 /* TODO: Because opendpi is a beta version now, so it should be changed later. */
extern unsigned long protocol_counter[];
#define TIME_INTERVAL 5
static unsigned long time1 = 0;
static unsigned long time2 = 0;

int opendpi_packets_top5_ops(struct msg *msg)
{
	log_info("begin opendpi_packets_top5_ops.");

	return 0;
}

void *opendpi_packets_top5_loop(void *conf)
{
	log_info("begin opendpi_packets_top5_loop.");

	sql_init();

	while (1) {
		time2 = time(NULL);	
		if (time2 >= time1 + TIME_INTERVAL) {
			time1 = time2;

			struct packets_top_five ptf[5];
			int j;
			for (j = 0; j < 5; j++) {
				ptf[j].counter = 0;
				strcpy(ptf[j].name, "NULL");
			}
	
			unsigned int i;
			for (i = 0; i < IPOQUE_MAX_SUPPORTED_PROTOCOLS; i++) {
				if (i == PROTOCOL_UNKNOWN) {
					continue;
				}
	
				long long int min_counter = ptf[0].counter;
				int k = 0;
				for (j = 0; j < 5; j++) {
					if (ptf[j].counter < min_counter) {
						min_counter = ptf[j].counter;
						k = j;
					}		
				}	

				if (min_counter < protocol_counter[i]) {
					ptf[k].counter = protocol_counter[i];
					strcpy(ptf[k].name, prot_long_str[i]);
				}
			}

			char cmd[1024];
			int res;

			res = sql_query("drop table if exists PacketsTopFive");
			if(res) {
				printf("insert error %d : %s\n", sql_errorno(), sql_error());
			}

			res = sql_query("create table PacketsTopFive(protocolName char(64), protocolCounter bigint)");
			if(res) {
				printf("insert error %d : %s\n", sql_errorno(), sql_error());
			}

			sprintf(cmd, "insert into PacketsTopFive values(\"%s\", %lld)", "TEST", (long long int)0);
			res = sql_query(cmd);
			if(res)	{
				printf("insert error %d : %s\n", sql_errorno(), sql_error());
			}

			for (i = 0 ; i < 5; i++) {
				sprintf(cmd, "insert into PacketsTopFive values(\"%s\", %lld)", ptf[i].name, ptf[i].counter);
				res = sql_query(cmd);
				if(res) {
					printf("insert error %d : %s\n", sql_errorno(), sql_error());
				}
			}
		}
	}

}
